<?php

uses('sanitize');

class StripsController extends AppController
{
	var $name = 'Strips';
	var $uses = array('Strip');
	var $helpers = array('Html', 'Time', 'Form', 'Bbcode');
	
	function listify($data)
	{
	    return '<ol><li>' . str_replace("\n", '</li><li>', trim($data)) . '</li></ol>';
	}
	
	function sanitize($strip)
	{
		$sanitize = new Sanitize();
	
		$strip['Strip']['annotation'] = $sanitize->html($strip['Strip']['annotation']);
		$strip['Strip']['transcript'] = $this->listify($sanitize->html($strip['Strip']['transcript']));
        
		return $strip;
	}
    
	function sanitizeSave($quote)
	{
		$sanitize = new Sanitize();
	
		return $quote;
	}
    
	function index($strip = 0)
   	{
		$this->Strip->recursive = 2;
	
		if($strip)
		{
		    $this->Strip->id = $strip;
		    $current = $this->Strip->read();
		    $this->Strip->recursive = 0;
		}
		
   		list($last) = $this->Strip->findAll(null, null, 'id DESC', 1);
		
		if(!$strip)
		{
		    $current = $last;
		}
   		
		$this->set('lastid', $last['Strip']['id']);
		$this->set('strip', $this->sanitize($current));
		$this->set('title', 'Strip #' . $current['Strip']['id'] . ': ' . $current['Strip']['title']);
		$this->render();
   	}
	
	function archive()
	{
	    $strips = $this->Strip->findAll(null, null, 'id DESC');
	    
	    $this->set('strips', $strips);
	    $this->set('title', 'Strip archive');
	}
   	
   	function add()
	{
		$this->checkLock();
		$this->checkRights();

		if(!empty($this->data['Strip']))
		{
			$file = $this->data['Upload']['filename'];
			
			if(!$this->isJpegImage($file))
			{
				$this->Strip->invalidate('filename', 'The uploaded file should be a correct JPEG image.');
			}
			else
			{
				$this->data = $this->sanitizeSave($this->data);
				
				if($this->Strip->save($this->data['Strip']))
				{
					move_uploaded_file($file['tmp_name'],
						sprintf('/storage/home/lucidfox/htdocs/qdb/app/webroot/img/strips/%02d.jpg', $this->Strip->id));
							
					$this->flash('The strip has been added.', '/strips/');
							exit();
				}
			}
		}
	}
   	
   	function edit($id)
	{
		$this->checkLock();
		$this->checkRights();

		if(empty($this->data['Strip']))
		{
		    $this->Strip->id = $id;
		    $this->data = $this->Strip->read();
		    $this->set('edit', true);
		    $this->render('add');
		}
		else
		{
				$this->data = $this->sanitizeSave($this->data);
				$this->data['Strip']['id'] = $id;
				
				if($this->Strip->save($this->data['Strip']))
				{
					$this->flash('The strip descruiption has been edited.', '/strips/');
							exit();
				}
		}
	}
	
	function isJpegImage($val)
	{
		if ((isset($val['error']) && $val['error'] == 0) ||
		(!empty($val['tmp_name']) && $val['tmp_name'] != 'none'))
		{
			return is_uploaded_file($val['tmp_name']) && exif_imagetype($val['tmp_name']) == IMAGETYPE_JPEG;
		}
		else
		{
		return false;
		}
	}
}

?>
